package com.xwqiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xwqiang.handle.AppException;
import com.xwqiang.mapper.SysPermMapper;
import com.xwqiang.mapper.SysUserMapper;
import com.xwqiang.pojo.model.AuthorSysUser;
import com.xwqiang.pojo.model.SysUser;
import com.xwqiang.utils.ErrCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


/**
 * 改造前
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermMapper sysPermMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //通过查询库将SysUser 封装成 AuthorSysUser
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

        log.info("-----sysUser:{}",sysUser);

        //如果没有对应的用户
        if (Objects.isNull(sysUser)) {
            throw new AppException(ErrCode.USER_NAME_PWD_ERROR);
        }

        List<String> perms;
        if(Objects.equals(sysUser.getUsername(), "admin")){
            //超管
            perms = sysPermMapper.getPermsAll();
        }else{
            perms = sysPermMapper.getSysUserPerms(sysUser.getId());
        }
        return new AuthorSysUser(sysUser,perms);
    }
}
